import React, { PureComponent } from 'react'
import { Form, Row, Col, Input, Button, Select, DatePicker, InputNumber } from 'antd'
import moment from 'moment'
import * as R from 'ramda'
// import store from '../../../index'
import { connect } from 'dva'
import { transferOption, isNotEmptyAndNil } from '@/utils/common'
import styles from './index.less'
import {F} from "ramda";

// const { dispatch } = store // todo: dispatch
const { RangePicker } = DatePicker
const FormItem = Form.Item
const dateFormat = 'YYYY-MM-DD HH:mm:ss'

// @Form.create()
@connect()
export default class PateoSearchNewForm extends PureComponent {

  handleSearch = fieldsValue => {
    const { fetchUrl, payloadUrl, saveFormValues, dateFormatList, dateFormatListNoTime, handleRangePicker, handleFieldsValue, formCallBack } = this.props

    // 自定义数据处理方法。必须return处理之后的数据才会提交，否则不提交
    const values = handleFieldsValue ? handleFieldsValue(fieldsValue) : {...fieldsValue};
    if(!values) return;

    for (let para in fieldsValue) {
      if (!fieldsValue[para] || !fieldsValue[para].toString().trim()) {
        fieldsValue[para] = undefined
      }
    }

    if (handleRangePicker) {
      const rangePicker = handleRangePicker(fieldsValue)
      if (isNotEmptyAndNil(rangePicker)) return
    }

    // dateFormatList:是用来格式化时间的
    if (dateFormatList) {
      dateFormatList.map(title => fieldsValue[title] ?
        (fieldsValue[title] = moment(fieldsValue[title]).format('YYYY-MM-DD HH:mm:ss')) : (fieldsValue[title] = undefined))
    }

    // dateFormatListNoTime:是用来格式化日期的
    if (dateFormatListNoTime) {
      dateFormatListNoTime.map(title => fieldsValue[title] ?
        (fieldsValue[title] = moment(fieldsValue[title]).format('YYYY-MM-DD')) : (fieldsValue[title] = undefined))
    }

    // saveFormValues:子组件向父组件传递表单的数据 和 dateFormatList 的顺序不可颠倒。
    if (saveFormValues) saveFormValues(fieldsValue)

    this.props.dispatch({
      type: fetchUrl,
      payload: payloadUrl ? Object.assign(payloadUrl, fieldsValue) : fieldsValue,
      callback: (response) => {
        if (formCallBack) {
          formCallBack(response);
        } else {
          return;
        }
      }
    })
  }

  handleFormReset = () => {
    let { fetchUrl, payloadUrl, handleFormReset, params } = this.props
    if (params) {
      payloadUrl = {
        ...payloadUrl,
        ...params,
      }
    }
    this.refs.form.resetFields()
    if (handleFormReset) { handleFormReset(this.refs.form) }
    this.props.dispatch({
      type: fetchUrl,
      payload: payloadUrl || {}
    })
  }

  loopFormItems = data => data.map(item => {    
    const { formDivId } = this.props
    let divId = formDivId ? formDivId : "public";
    const { title, key, type, specialStyle } = item
    switch (type) {
      case 'between': {
        return (
          <Col md={specialStyle || 8} sm={24} key={key}>
            <FormItem
              key={key}
              label={title}
            >
              <FormItem name={key.split('-')[0]} noStyle>
                <InputNumber style={{
                  margin: 0,
                  width: '42%',
                  borderBottomRightRadius: 0,
                  borderTopRightRadius: 0,
                  textAlign: 'center'
                }} placeholder="最小值" />
              </FormItem>
              <FormItem noStyle>
                <Input
                  style={{
                    width: '16%',
                    borderRadius: 0,
                    borderLeft: 0,
                    pointerEvents: 'none',
                    backgroundColor: '#fff',
                    textAlign: 'center',
                    margin: '-1px 0 0 0'
                  }}
                  placeholder="~"
                  disabled
                />
              </FormItem>
              <FormItem name={key.split('-')[1]} noStyle>
                <InputNumber style={{
                  margin: 0,
                  width: '42%',
                  borderBottomLeftRadius: 0,
                  borderTopLeftRadius: 0,
                  textAlign: 'center',
                  borderLeft: 0
                }} placeholder="最大值" />
              </FormItem>
            </FormItem>
          </Col>
        )
      }
      case 'input': {
        const placeholder = `请填写${typeof (title) === 'string' ? title : ''}`
        return (
          <Col md={specialStyle || 8} sm={24} key={key}>
            <FormItem
              key={key}
              label={title}
              name={key}
            >
              <Input placeholder={placeholder} />
            </FormItem>
          </Col>
        )
      }
      case 'select': {
        const { selectOptions, keyValue, onSelectChange, initialValue, cantClear, specialStyle,...rest } = item
        const options = { initialValue }
        return (
          <Col md={specialStyle || 8} sm={24} key={key}>
            <FormItem key={key} label={title} name={key} {...options}>
              <Select
                placeholder='请选择'
                showSearch
                filterOption={(input, option) => option && option.props && option.props.children && option.props.children.indexOf(input) >= 0}
                allowClear={!cantClear}
                onChange={onSelectChange}
                //getPopupContainer={triggerNode => triggerNode.parentNode}
                getPopupContainer={() => document.getElementById(divId)}
                {...rest}
              >
                {transferOption(selectOptions, keyValue)}
              </Select>
            </FormItem>
          </Col>
        )
      }
      case 'datePicker': {
        const { nohmsFormat, noTimeSelect } = item
        return (
          <Col md={8} sm={24} key={key}>
            <FormItem key={key} label={title} name={key}>
              <DatePicker
                showTime={!noTimeSelect}
                format={nohmsFormat ? nohmsFormat : dateFormat}
                showToday
                getCalendarContainer={trigger => trigger.parentNode}
              />
            </FormItem>
          </Col>
        )
      }
      case 'rangePicker': {
        // 这里不再推荐使用noTimeSelect,showTime,
        const { nohmsFormat, noTimeSelect, specialStyle, disabledDate, disabledTime, showTime, style, initialValue, noRanges } = item
        const options = { initialValue }
        return (
          <Col md={specialStyle || 8} sm={24} key={key}>
            <FormItem key={key} label={title} name={key} {...options}>
              <RangePicker
                style={style}
                disabledDate={disabledDate}
                disabledTime={disabledTime}
                showTime={R.isNil(showTime) ? !noTimeSelect : showTime}
                format={nohmsFormat ? nohmsFormat : dateFormat}
                placeholder={['开始时间', '结束时间']}
                ranges={noRanges ? {} :{
                  '本周 ': [moment().startOf('weeks'), moment()],
                  '最近一周 ': [moment().add(-1, 'weeks'), moment()],
                  '本月 ': [moment().startOf('months'), moment()],
                  '最近一个月 ': [moment().add(-1, 'months'), moment()],
                }}
                getCalendarContainer={trigger => trigger.parentNode}
              />
            </FormItem>
          </Col>
        )
      }
      //这个是用来调整格式的
      case 'blank': {
        return (
          <Col md={8} sm={24} key={key}>
            <FormItem key={key}>
            </FormItem>
          </Col>
        )
      }
    }
  })

  format = () => {
    const { searchItems = [] } = this.props
    let item  = this.loopFormItems(searchItems);
    let count = Math.ceil(searchItems.length/3);
    let list = [];
    for(let i=1;i<=count;i++) {
      let result = '';
      if (i===count) {
        result = <Row key={i} gutter={{ md: 8, lg: 24, xl: 48 }}>
          {item.slice((i-1)*3,3*i)}
          <Col>
              <span className={styles.expendButtons}>
                <Button type='primary' htmlType='submit'>查询</Button>
                <Button style={{ marginLeft: 8 }} onClick={this.handleFormReset}>重置</Button>
              </span>
          </Col>
        </Row>
      } else {
        result = <Row key={i} gutter={{ md: 8, lg: 24, xl: 48 }}>
          {item.slice((i-1)*3,3*i)}
        </Row>
      }
      list.push(result);
    }
    return list;
  }

  renderForm = () => {
   return this.format().map(item=>item)
  }


  render() {
    const { formDivId } = this.props;
    let divId = formDivId ? formDivId : "public";
    return (
      <div className={styles.tableListForm} id={divId}>
        <Form onFinish={this.handleSearch} layout='inline' ref="form">
          {this.renderForm()}
        </Form>
      </div>
    )
  }
}

